package com.lagou.exam;

import java.io.*;
import java.util.*;

// 自定义一个管理器，负责管理所有考题；目前只有选择题
public class ExamManager {

    // 所有学员信息，用集合来维护--可以map 可以list
    private Map<Integer, ExamQuestion> questions = new HashMap<>();
    private String saveQuestionPath = "/home/keats/test/examQuestions.txt";

    public ExamManager() {
        loadQuestionsFromFile();
    }

    // 自定义考题的增删查改，管理的个体是ExamQusetion
    void addExamQuestion(ExamQuestion question) {
        // 检查数据有效性，且不存在该名字对应的学生
        if(null != question && question instanceof ExamQuestion
                && !questions.containsKey(question.getId())) {
            questions.put(question.getId(), question);
            System.out.println("添加考题" + question.getId() + "成功");
            return ;
        }
        System.out.println("数据有误，或已存在" +question.getId() + "考题信息"); // 是否需要抛出什么消息，回复客户端
    }

    void deleteExamQuestion(int id) {
        if(questions.containsKey(id)) {
            ExamQuestion question = questions.remove(id);
            System.out.println("成功删除考题：" + question );
            return;
        }
        System.out.println("不存在" + id + "对应的考题");
    }

    ExamQuestion findExamQusetion(int id) {
        if(questions.containsKey(id)) {
            ExamQuestion question = questions.get(id);
            return question;
        }
        System.out.println("不存在" + id + "对应的考题");
        return null;
    }

    void updateExamQusetion(int id, ExamQuestion question) {
        // 检查数据有效性，且存在该名字对应的学生
        if(null != question && question instanceof ExamQuestion
                && questions.containsKey(id)) {
            // 先获取考题，考题内容是
            ExamQuestion question1 = questions.get(id);
            question1.modify(question1);
            //question1.modify(question1.getScore());
            System.out.println("服务器修改" + id + "对应考题成功");
            return ;
        }

        System.out.println("不存在" + id + "对应的考题");
    }

    /**
     * 从文件读取考题，也算导入考题；导入源为文件，导入的是之前就有的考题
     */
    private void loadQuestionsFromFile() {
        ObjectInputStream ois = null;
        try {
            // 1.创建ObjectInputStream类型对象和文件关联

            FileInputStream fileInputStream = new FileInputStream(saveQuestionPath);
            ois = new ObjectInputStream(fileInputStream);

            // 2.从输入流中读取一个对象
            Object obj = ois.readObject();
            System.out.println("读取到的学员信息是：" + obj);
            if(obj instanceof Map)
            {
                Map tmpArrayList = (Map) obj;
                // 获取Map集合中所有键值对并组成Set视图
                Set<Map.Entry<Integer, ExamQuestion>> entries = tmpArrayList.entrySet();
                for (Map.Entry<Integer, ExamQuestion> me : entries) {
                    System.out.println("数据库读取到学员信息：" + me);
                    questions.put(me.getKey(), me.getValue());
                }
                System.out.println("读取数据库，添加完数据之后，所有学员数量为：" + questions.size());
            }

        } catch (FileNotFoundException e) {
            System.out.println("数据库文件不存在！");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 3.关闭对象并释放有关资源
            if (null != ois) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 保存学员信息到文件中
     */
    public void saveQuestionsTofile() {
        ObjectOutputStream oos = null;
        try {
            // 1.创建ObjectOutputStream类型对象和文件关联
            File file = new File(saveQuestionPath);
            if(!file.exists()) {
                File path = new File(file.getParent());
                if(!path.exists()) {
                    path.mkdirs();
                }
                file.createNewFile();
                //文件不存在，创建
                System.out.println("创建文件" + saveQuestionPath + "成功！");
            }
            oos = new ObjectOutputStream(new FileOutputStream(saveQuestionPath));

            // 2.准备一个对象 arrayList ArrayList类型
            // 3.将整个集合类型对象写入输出流
            oos.writeObject(questions);
            System.out.println("保存了" + questions.size() + "个考题数据");
            System.out.println("写入集合对象（序列化）成功！");
        } catch (IOException e) {
            e.printStackTrace(); // NotSerializableException 可能报这个异常
            // NotSerializableException 需要序列化哦
        } finally {
            // 4.关闭流对象并释放有关的资源
            if (null != oos) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    ExamQuestion generateExamQuestion() {
        ExamQuestion question = new ExamQuestion();
        question.modify(ServerRandom.getRandomScore());
        return question;
    }

    ExamPaper generateExamPaper() {
        // 先按照map的values转换为数组，然后转化为list，然后在打乱，随机获取十道题
        // 根据十道题目，创建一个试卷
        ExamQuestion[] objects = (ExamQuestion[]) questions.values().toArray();
        List<ExamQuestion> questions = Arrays.asList(objects);
        Collections.shuffle(questions);

        List<ExamQuestion> questionList = questions.subList(0, 10);

        return new ExamPaper(questionList);
    }


    // 测试程序，测试当前类的增删查改功能
    public static void main(String[] args) {
        ExamManager em = new ExamManager();

        /*//先随机出100道题目，可能有重复
        for (int i = 0; i < 100; i++ ) {
            em.addExamQuestion(em.generateExamQuestion());
        }
        System.out.println("考题数量" + em.questions.size());
        ExamQuestion question = em.generateExamQuestion();
        em.addExamQuestion(question);
        System.out.println("考题数量" + em.questions.size());
        System.out.println("查找试题：" + em.findExamQusetion(question.getId()));

        // 修改试题，目前只支持修改分值
        em.updateExamQusetion(question.getId(), em.generateExamQuestion());
        System.out.println("考题数量" + em.questions.size());

        // 删除试题
        em.deleteExamQuestion(question.getId());
        System.out.println("考题数量" + em.questions.size());

        em.saveQuestionsTofile();*/


    }
}

